package aex.service;



import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import aex.dao.UserMailDao;
import aex.domain.Puser;
import aex.domain.UserMail;
import aex.util.CU;



@Transactional(readOnly = false)
@Service(UserMailService.SERVICE_NAME)

public class UserMailService  {

	
	public static final String SERVICE_NAME="aex.service.UserMailService";
	/**
	 * 以注解的形式让spring为我们注入dao的实现类
	 */
	@Resource(name = UserMailDao.SERVICE_NAME)
	public UserMailDao dao;
	
	public UserMailService() {
		
	}
	public UserMail findByID(Serializable id) {
		return dao.findObjectByID(Integer.parseInt(id+""));
	}
	public void deleteById(Serializable id) {
		dao.deleteObjectByIDs(Integer.parseInt(id+""));
	}
	public void save(UserMail obj) {
		dao.save(obj);
	}
	public void update(UserMail obj) {
		dao.merge(obj);
	}
	
	/**
	 * 获取用户和对方的所有消息，按照时间排序
	 * @param puId
	 * @param herId
	 * @return
	 */
	public List<UserMail> findMail(Integer puId, String herId) {
		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("tName.umTime", "asc");
		return dao.findCollectionByConditionNoPage(" and ( tName.puserByPuAcceput="+puId +"and tName.puserByPuSend="+herId+")"
										   + "or (tName.puserByPuAcceput="+herId +"and tName.puserByPuSend="+puId+")" , null, orderby);
		
	}
	public List<Puser> getContacts(Integer puId) {
		List<Puser> contacts=new ArrayList<Puser>();
		List<UserMail> mails=new ArrayList<UserMail>();

		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("tName.umTime", "asc");
		
		mails=dao.findCollectionByConditionNoPage(" and tName.puserByPuAcceput="+puId +" or  tName.puserByPuSend="+puId , null, orderby);
		
		for (UserMail userMail : mails) {
			
			boolean flag=true;
			
			if(userMail.getPuserByPuAcceput().getPuId().equals(puId)){ //我是接受者，看对方是否被添加
			  
				for (Puser contact : contacts) {
					if(userMail.getPuserByPuSend().getPuId()==contact.getPuId()){//只要有一个等于，就跳出循环
						flag=false;
						continue;
					}
				
				}
			
				if(flag){//如果最后标记还没有改变 那么这条记录是新的
					contacts.add(userMail.getPuserByPuSend());
				}
			
			}else if(userMail.getPuserByPuSend().getPuId().equals(puId)){ //我是接受者，看对方是否被添加
				for (Puser contact : contacts) {
						if(userMail.getPuserByPuAcceput().getPuId()==contact.getPuId()){//只要有一个等于，就跳出循环
							flag=false;
							continue;
						}
					
					}
				if(flag){//如果最后标记还没有改变 那么这条记录是新的
					contacts.add(userMail.getPuserByPuAcceput());
				}
			}
		}
		return contacts;
	}
}
